//
//  WD_BulletView.m
//  BUDING
//
//  Created by HanWoonYong on 16/4/12.
//  Copyright © 2016年 HanWoonYong. All rights reserved.
//

#import "WD_BulletView.h"
#define WIDTH [UIScreen mainScreen].bounds.size.width
#define HEIGHT [UIScreen mainScreen].bounds.size.height
@interface WD_BulletView ()

@property (nonatomic, strong)UILabel *guided;

@end

@implementation WD_BulletView

- (void)dealloc
{
    [self stopFire];
    self.fireBlock = nil;
}

- (instancetype)initWithContent:(NSString *)content
{
    //    self = [super init];
    if (self = [super init]) {
        NSDictionary *attribute = @{NSFontAttributeName:[UIFont systemFontOfSize:15]};
        float width = [content sizeWithAttributes:attribute].width;
        self.bounds = CGRectMake(0, 0, width, 30);
        self.guided = [[UILabel alloc] init];
        self.guided.frame = CGRectMake(0, 0, (width), 30);
        self.guided.text = content;
        self.guided.textColor = [UIColor whiteColor];
        self.guided.font = [UIFont systemFontOfSize:15];
        [self addSubview:self.guided];
    }
    return self;
}

- (void)startFire {
    CGFloat width = CGRectGetWidth(self.frame) + WIDTH + 50;
    CGFloat speed = width / 10;
    CGFloat duration = (CGRectGetWidth(self.frame) + 50) / speed;
    __block CGRect frame = self.frame;
    if (self.fireBlock) {
        self.fireBlock(Start);
    }
    // dutation一段时间在主线程执行一段代码
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(duration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //duration时间后弹幕大军完全进入
        if (self.fireBlock) {
            self.fireBlock(Enter);
        }
        
    });
    
    // 弹幕大军完全离开
    [UIView animateWithDuration:5 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
        frame.origin.x = - CGRectGetWidth(frame);
        self.frame = frame;
    } completion:^(BOOL finished) {
        if (self.fireBlock) {
            self.fireBlock(End);
        }
        [self removeFromSuperview];
    }];
}

- (void)stopFire {
    [self.layer removeAllAnimations];
    [self removeFromSuperview];
}

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

@end

